package be.sc.classicnetwork.service.impl;

import java.util.Collection;

import be.sc.classicnetwork.model.Car;
import be.sc.classicnetwork.model.Contact;
import be.sc.classicnetwork.service.CarService;
import be.sc.classicnetwork.service.MailService;
import freemarker.template.SimpleHash;

/**
 * 
 */
public class EmailCarNotficationTask implements Runnable {
	private static final String NOTIFICATION_TEMPLATE = "carNotification.ftl";

	private CarService carService;
	private MailService mailService;
	private Car car;
	private String from;
	private String fromPersonal;
	private String subject;
	private String rootUrl;

	/**
	 * Constructor.
	 */
	public EmailCarNotficationTask(CarService carService,
			MailService mailService, Car car, String from, String fromPersonal,
			String rootUrl, String subject) {
		super();
		this.carService = carService;
		this.mailService = mailService;
		this.car = car;
		this.from = from;
		this.fromPersonal = fromPersonal;
		this.subject = subject;
		this.rootUrl = rootUrl;
	}

	/**
	 * @see java.lang.Runnable#run()
	 */
	@SuppressWarnings("unchecked")
	public void run() {
		// put the car info as model for freemarker template
		SimpleHash model = new SimpleHash();
		model.put("car", car);
		model.put("rootUrl", rootUrl);

		// get the contact that will receive the notification
		Collection<Contact> contacts = carService
				.findContactsForNotification(car.getId());

		// send mail to contacts for notification
		for (Contact contact : contacts) {
			model.put("contact", contact);
			mailService.sendFreeMarkerTemplate(from, fromPersonal, contact
					.getEmail(), subject, null, NOTIFICATION_TEMPLATE, model);
		}

	}

}
